<template>
	<view>
		<button type="primary" @click="shenfenzheng">身份证识别</button>

		<view class="result-item">
			<text>类型：{{type || '未识别'}}</text>
		</view>
		<view class="result-item">
			<text>姓名：{{name || '未识别'}}</text>
		</view>
		<view class="result-item">
			<text>身份证编码：{{id || '未识别'}}</text>
		</view>
		<view class="result-item">
			<text>地址：{{addr || '未识别'}}</text>
		</view>
		<view class="result-item">
			<text>性别：{{gender || '未识别'}}</text>
		</view>
		<view class="result-item">
			<text>民族：{{nationality || '未识别'}}</text>
		</view>
		<view class="result-item">
			<text>出生日期：{{birth || '未识别'}}</text>
		</view>
		<view class="result-item">
			<text>身份证几代：{{cardProperty || '未识别'}}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				type: "",
				name: "",
				id: "",
				addr: "",
				gender: "",
				nationality: "",
				birth: "",
				cardProperty: 4
			}
		},
		methods: {
			shenfenzheng() {
				this.photo("shenfenzheng")
			},
			photo(type) {
				let that = this
				wx.chooseMedia({
					count: 1,
					mediaType: ['image', 'video'],
					sourceType: ['album', 'camera'],
					success(res) {
						// tempFilePath可以作为img标签的src属性显示图片
						let imgUrl = res.tempFiles[0].tempFilePath;
						console.log("res.tempFiles[0].tempFilePath" + res.tempFiles[0].tempFilePath)
						console.log("res.tempFiles[0].size)" + res.tempFiles[0].size)
						that.uploadImg(type, imgUrl)
					}
				})
			},
			uploadImg(type, imgUrl) {
				let that = this
				wx.cloud.uploadFile({
					cloudPath: 'ocr/' + type + '.png',
					filePath: imgUrl, // 文件路径
					success: res => {
						console.log("上传成功", res.fileID)
						that.getImgUrl(type, res.fileID)
					},
					fail: err => {
						console.log("上传失败", err)
					}
				})
			},
			getImgUrl(type, imgUrl) {
				let that = this
				wx.cloud.getTempFileURL({
					fileList: [imgUrl],
					success: res => {
						let imgUrl = res.fileList[0].tempFileURL
						console.log("获取图片url成功:", imgUrl + "获取图片type成功:" + type)
						that.shibie(type, imgUrl)
					},
					fail: err => {
						console.log("获取图片url失败", err)
					}
				})
			},
			shibie(type, imgUrl) { 
				wx.cloud.callFunction({
					name: "quickstartFunctions",
					data: {
						type,
						imgUrl
					},
					success: (res) => {
						this.type = res.result.type,
						this.name= res.result.name,
						this.id=res.result.id,
						this.addr=res.result.addr,
						this.gender=res.result.gender,
						this.nationality=res.result.nationality,
						this.birth=res.result.birth,
						this.cardProperty= res.result.cardProperty
					},
					fail: console.error
				})
			}  
		}
	}
</script>

<style>
</style>